package com.example.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class InitializingAdvice implements InitializingBean {

    @Autowired
    private RequestMappingHandlerAdapter adapter;

    @Override
    public void afterPropertiesSet() throws Exception {
        List<HandlerMethodReturnValueHandler> returnValueHandlers = adapter.getReturnValueHandlers();
        List<HandlerMethodReturnValueHandler> handlers = new ArrayList(returnValueHandlers);
        this.decorateHandlers(handlers);
        adapter.setReturnValueHandlers(handlers);
    }

    /**
     * 替换spring原有的RequestResponseBodyMethodProcessor为自定义的
     * WebApiHandlerMethodReturnValueHandler 以支持自定义注解@WebApiResponseBody
     *
     * @param handlers
     */
    private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
        for (HandlerMethodReturnValueHandler handler : handlers) {
            if (handler instanceof RequestResponseBodyMethodProcessor) {
                List<HttpMessageConverter<?>> converters = new ArrayList<>();
                converters.add(new FastJsonHttpMessageConverter());
              //  WebApiRequestResponseBodyMethodProcessor methodProcessor = new WebApiRequestResponseBodyMethodProcessor(converters);
                WebApiHandlerMethodReturnValueHandler returnValueHandler=new WebApiHandlerMethodReturnValueHandler();

                int index = handlers.indexOf(handler);
                handlers.set(index, returnValueHandler);
                break;
            }
        }
     //   FastJsonHttpMessageConverter
       // handlers.add(new WebApiHandlerMethodReturnValueHandler());
    }
}
